#include "tree.h"

bool start( char *parse_fn, char *plain_fn, char *out_fn )
{
	CUTextFile parse_file( parse_fn, "r" );
	if( parse_file.IsOpen() == false )	return false;

	CUTextFile plain_file( plain_fn, "r" );
	if( plain_file.IsOpen() == false )	return false;

	CUTextFile out_file( out_fn, "w" );
	if( out_file.IsOpen() == false )	return false;

	int now_line=0;
	while(1)	{
		CUString line;
		if( parse_file.ReadLine( line ) == false ) break;

		CUString line2;
		if( plain_file.ReadLine( line2 ) == false ) break;
		CUStringListSN orgTok( line2, " " );
		now_line++;


		CTree t ;
		t.Init();
		if( t.LoadTree( line ) == false )	{
			fprintf( stderr, "load fail: %d\n", now_line );
			fprintf( out_file.GetFP(), "INVALID TREE\n" );
			fflush( out_file.GetFP() );
			continue;
		}


		int ls[NUM_MAX_NODE];
		int s;


		t.GetLexNodeList( ls, s, ROOT_ID );
		if( s != orgTok.GetSize() )
		{
			fprintf( stderr, "Warn: %d %d vs %d\n", now_line, s, orgTok.GetSize() );
			fprintf( out_file.GetFP(), "\n" ); fflush( out_file.GetFP() );
			continue;
		}

		for( int i=0; i<s; i++ )	{
			CNode &n = t.node[ ls[i] ];
			CNode &p = t.node[ n.parent ];

			if( n.label != orgTok.GetAt(i) )
			{
				fprintf( stderr, "Warn: %d\n%s\n%s\n", now_line, line.GetStr(), line2.GetStr() );
				/*
				for( int j=0; j<s; j++ )
				{
					fprintf( stderr, "%s\n", t.node[ ls[j] ].label.GetStr() );
				}
				break;
				*/

				n.label = orgTok.GetAt(i);
			}
		}
		t.PrintParse2File( out_file );
//		fprintf( out_file.GetFP(), "\n" ); fflush( out_file.GetFP() );

	}



	return true;
}


int main( int argc, char *argv[] )
{
	if( argc != 4 )	{
		fprintf( stderr, "usage: %s parse-file plain-file out-file\n", argv[0] );
		return 1;
	}

	if( start( argv[1], argv[2], argv[3] ) == false )	{
		return 1;
	}

	return 0;
}


